import { useEffect, useRef, useState } from "react";
import "./Login.scss";
import { message } from "antd";
import { postLogin, postSign } from "@s/api/apis";
import type { userT } from "./detail/PersonCenter";

function login(props: { setLogin: (val: boolean) => void }) {
  const { setLogin } = props;
  const [messageApi, contextHolder] = message.useMessage(); // 提示警告
  const [state, setState] = useState(1); // 1代表登录状态 / 2代表注册
  const [userData, setUserData] = useState<userT | null>(null);
  const inpCount = useRef<any>(null);
  const inpPassword = useRef<any>(null);
  function changeS() {
    if (state == 1) setState(2);
    else setState(1);
  }
  function affirm() {
    if (!inpCount.current?.value || !inpPassword.current?.value) {
      messageApi.open({
        type: "error",
        content: "输入用户名和密码",
      });
      return;
    }
    // 登录
    if (state == 1) {
      postLogin({
        userName: inpCount.current?.value,
        password: inpPassword.current?.value,
      })
        .then((res: any) => {
          // console.log(res, "请求成功");
          // TODO:
          if (res?.code == 200) {
            localStorage.setItem("userName", inpCount.current?.value);
            localStorage.setItem("password", inpPassword.current?.value);
            localStorage.setItem("Uid", res.data[0].Uid);
            localStorage.setItem("token", res.token);
            setLogin(true);
            messageApi.open({
              type: "success",
              content: "登录成功s",
            });
          } else {
            messageApi.open({
              type: "error",
              content: "用户名或者密码错误",
            });
          }
        })
        .catch((err) => {
          messageApi.open({
            type: "error",
            content: "出现异常",
          });
          console.error(err, "请求失败");
        });
    }
    // 注册
    else {
      postSign({
        userName: inpCount.current?.value,
        password: inpPassword.current?.value,
      })
        .then((res: any) => {
          // TODO:
          if (res.code == 200) {
            localStorage.setItem("userName", inpCount.current?.value);
            localStorage.setItem("password", inpPassword.current?.value);
            localStorage.setItem("token", res.token);
            setLogin(true);
            messageApi.open({
              type: "success",
              content: "注册成功",
            });
          } else {
            messageApi.open({
              type: "error",
              content: "注册失败，请更换用户名",
            });
          }
        })
        .catch((err) => {
          messageApi.open({
            type: "error",
            content: "出现异常",
          });
          console.error(err, "请求失败");
        });
    }
  }
  // function isTokenOk(val) {
  //   return new Promise<void>((resolve, reject) => {
  //     resolve({ data: 1 });
  //   });
  // }

  // 是否可以自动登录
  // useEffect(() => {
  //   let token = localStorage.getItem("token");
  //   if (token) {
  //     isTokenOk(token).then((res) => {
  //       if ((res as any).data) {
  //         setLogin(true);
  //       } else {
  //         return;
  //       }
  //     });
  //   }
  // }, []);

  // 是否可以自动登录
  useEffect(() => {
    if (localStorage.getItem("userName") && localStorage.getItem("password")) {
      setLogin(true);
    }
  }, []);
  return (
    <>
      <div className="login-box">
        <div className="changeR">切换管理员登录</div>
        {contextHolder}
        <h2> {state == 1 ? "用户登录" : "请注册"}</h2>
        <form>
          <div className="user-box">
            <input ref={inpCount} type="text" required />
            <label>账号</label>
          </div>
          <div className="user-box">
            <input ref={inpPassword} type="password" required />
            <label>密码</label>
          </div>
          <a href="#" onClick={changeS}>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            {state == 1 ? "切换注册" : "切换登录"}
          </a>
          <span></span>
          <a href="#" onClick={affirm}>
            <span></span>
            <span></span>
            <span></span>
            {state == 1 ? "登录" : "注册"}
          </a>
        </form>
      </div>
    </>
  );
}
export default login;
